//
//  CantripAppController.m
//  Cantrip
//
//  Created by James Callender on Sat Jun 05 2004.
//  Copyright (c) 2004 James Callender. All rights reserved.
//

#import "CantripAppController.h"

#define EXP_DATE @"2004-08-07 00:00:00 -0400"

@implementation CantripAppController

+ (void)initialize
{
    [[NSUserDefaults standardUserDefaults] registerDefaults:
		[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:@"ShowConsole"]];
}

+ (CantripAppController *)controller
{
    return [NSApp delegate];
}

- (void)applicationWillFinishLaunching:(NSNotification *)notification
{
    NSExceptionHandler *handler = [NSExceptionHandler defaultExceptionHandler];
    [handler setExceptionHandlingMask:NSLogAndHandleEveryExceptionMask];
    [handler setDelegate:self];
    
    [[CantripPluginManager sharedPluginManager] loadAllBundles];
}

- (void)applicationDidFinishLaunching:(NSNotification *)notification
{
    NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
    NSEnumerator *pluginsEnumerator, *settingsModulesEnumerator;
    id plugin, settingsModule;
    
    [self log:@"Cantrip starting up...\n"];
	/*
	 NSLog(@"%@ %@", [[NSDate dateWithString:EXP_DATE] description], [[NSDate date] description]);
	 if ([[NSDate dateWithString:EXP_DATE] compare:[NSDate date]] == NSOrderedAscending) {
		 NSRunAlertPanel(@"Expired", @"This demo version of cantrip has expired", @"Quit", @"", @"");
		 [NSApp terminate:self];
	 }
	 */
	
    [oConsolePanel setLevel:NSNormalWindowLevel];
    [oConsolePanel setHidesOnDeactivate:YES];
    if ([preferences boolForKey:@"ShowConsole"])
    {
		[oConsolePanel makeKeyAndOrderFront:self];
		[oConsoleMenuItem setTitle:NSLocalizedString(@"HideConsole", @"The phrase 'Hide Console'")];
    }
    
    [[CantripWorldSettingsController sharedInstance] window];
    [[CantripBookmarkController sharedInstance] window];
    [[CantripBookmarkController sharedInstance] updateBookmarksMenu];
    if ([preferences boolForKey:@"showBookmarksAtStartup"])
		[[CantripBookmarkController sharedInstance] showPanel:self];
    
    pluginsEnumerator = [[[CantripPluginManager sharedPluginManager] pluginClasses] objectEnumerator];
    while (plugin = [pluginsEnumerator nextObject]) {
		settingsModulesEnumerator = [[plugin settingsModules] objectEnumerator];
		while (settingsModule = [settingsModulesEnumerator nextObject]) {
			[[CantripWorldSettingsController sharedInstance] addSettingsModule:settingsModule];
		}
    }
	
    [self updateWorldsMenu:nil];
    [[NSColorPanel sharedColorPanel] setShowsAlpha:YES];
}

- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)app
{
    return NSTerminateNow;
}

- (void)applicationWillTerminate:(NSNotification *)notification
{
    [self log:@"Cantrip terminating now...\n"];
}

- (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender
{
    return NO;
}

- (void)updateWorldsMenu:(id)notification
{ 
    NSEnumerator *enumerator; 
    NSFileWrapper *quickMenuDir, *currWrapper;
    NSDictionary *quickMenuDict;
    NSMenuItem *quickitem;
    NSString *basePath, *worldsPath;
    id key;
    
    worldsPath = [[NSUserDefaults standardUserDefaults] stringForKey:@"worldsMenuPath"];
    if ([worldsPath hasPrefix:@"/"]) basePath = worldsPath;
    else basePath = [[[[[NSBundle mainBundle] bundlePath] 
	    stringByDeletingLastPathComponent] stringByAppendingPathComponent:[[NSUserDefaults standardUserDefaults] stringForKey:@"worldsMenuPath"]]
	    stringByStandardizingPath];
    NSLog(basePath);
    while([oWorldsMenu numberOfItems])
        [oWorldsMenu removeItemAtIndex:0];
    
    [oWorldsMenu setAutoenablesItems:NO];
    
    quickMenuDir = [[NSFileWrapper alloc] initWithPath:basePath];
    
    if (quickMenuDir == nil)
    {
        quickitem = [[NSMenuItem alloc] 
            initWithTitle:@"none" action:NULL keyEquivalent:@""];
        [quickitem setEnabled:NO];
        [oWorldsMenu addItem:quickitem];
        
        [quickitem release];
		NSBeep();
        return;
    }
    
    quickMenuDict = [quickMenuDir fileWrappers];
    enumerator = [quickMenuDict keyEnumerator];
    
    while ((key = [enumerator nextObject])) 
    { 
        currWrapper = [quickMenuDict objectForKey:key];
        if ([currWrapper isRegularFile] && 
            [[[currWrapper filename] pathExtension] isEqualTo:@"cworld"])
        {
            NSImage *fileIcon = [[NSWorkspace sharedWorkspace] iconForFile:
                [basePath stringByAppendingPathComponent:[currWrapper filename]]]; 
            
            [fileIcon setSize:NSMakeSize(16,16)];
            quickitem = [[NSMenuItem alloc] 
                initWithTitle:[key stringByDeletingPathExtension] 
					   action:@selector(worldsMenuAction:) keyEquivalent:@""];
            
            [quickitem setEnabled:YES];
            [quickitem setTarget:self];
            [quickitem setRepresentedObject:
                [[basePath stringByAppendingPathComponent:[currWrapper filename]] retain]];
            [quickitem setImage:fileIcon];
            [oWorldsMenu addItem:quickitem];
            
            [quickitem release];
        }
        
    }
}

- (void)applicationDidBecomeActive:(NSNotification *)notification
{
    //[[NSNotificationCenter defaultCenter] postNotificationName:NSWindowDidBecomeMainNotification object:nil];
}

- (void)windowWillClose:(NSNotification *)notification
{
    if ([notification object] == oConsolePanel) {
		[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"ShowConsole"];
		[oConsoleMenuItem setTitle:NSLocalizedString(@"ShowConsole", @"The phrase 'Show Console'")];
    }
}

- (void)windowDidBecomeMain:(NSNotification *)notification
{
	
}

- (BOOL)exceptionHandler:(NSExceptionHandler *)sender
   shouldHandleException:(NSException *)exception mask:(unsigned int)aMask
{
    //NSLog(@"My handler");
    NSRunAlertPanel(@"An Error Occured", @"The following error has occured: %@", @"OK", @"", @"", exception);
}


#pragma mark Interface Actions

- (IBAction)showBookmarksPanel:(id)sender
{
    [[CantripBookmarkController sharedInstance] showPanel:self];
}

- (IBAction)showSettingsPanel:(id)sender
{
    [[CantripWorldSettingsController sharedInstance] showWindow:self];
}


- (IBAction)checkForUpdateAction:(id)sender
{
    NSString *currVersionNumber = [[[NSBundle bundleForClass:[self class]]
		infoDictionary] objectForKey:@"CFBundleVersion"];
    NSDictionary *productVersionDict = [NSDictionary dictionaryWithContentsOfURL:
		[NSURL URLWithString:@"http://www.solidsun.com/cm/vers.xml"]];
    NSDictionary *cantripVersionDict;
    NSString *latestVersionNumber, *versionComments;
    
    // @"An error occured while accessing the version information.  Perhaps you are not connected to the internet."
    if (productVersionDict == nil) {
		NSRunAlertPanel(NSLocalizedString(@"NetworkErrorTitle", @"The title of a panel: 'Network Error'"),
						NSLocalizedString(@"NetworkErrorNotice", @"Error occured getting version information."),
						NSLocalizedString(@"OK", none), nil, nil);
		return;
    }
    
    cantripVersionDict = [productVersionDict objectForKey:@"cantrip"];
    latestVersionNumber = [cantripVersionDict valueForKey:@"version"];
    versionComments = [cantripVersionDict objectForKey:@"comments"];
    if (versionComments == nil) {
		versionComments = @"No additional information.";
    }
    
    // @"You have the latest version of Cantrip."
    if ([latestVersionNumber isEqual:currVersionNumber]) {
		NSRunInformationalAlertPanel(NSLocalizedString(@"UpToDate", @"The title of a panel: 'Up To Date'"), 
									 NSLocalizedString(@"LatestVersionNotice", @"The user has the latest version of cantrip."),
									 NSLocalizedString(@"OK", none), nil, nil);
    } else {
		[oUpdatePanel center];
		[oUpdateTextArea setString:versionComments];
		[oUpdatePanel makeKeyAndOrderFront:self];
    }
}

- (IBAction)downloadButtonAction:(id)sender
{
    [[NSWorkspace sharedWorkspace] openURL:[NSURL
	    URLWithString:@"http://www.solidsun.com/cm/"]];
}

- (IBAction)ignoreButtonAction:(id)sender
{
    [oUpdatePanel orderOut:self];
}

- (IBAction)toggleConsoleAction:(id)sender
{
    if ([oConsolePanel isVisible]) {
		[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"ShowConsole"];
		[oConsoleMenuItem setTitle:NSLocalizedString(@"ShowConsole", @"The phrase 'Show Console'")];
		[oConsolePanel orderOut:self];
    } else {
		[oConsolePanel makeKeyAndOrderFront:self];
		[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"ShowConsole"];
		[oConsoleMenuItem setTitle:NSLocalizedString(@"HideConsole", @"The phrase 'Hide Console'")];
    }
}

- (IBAction)worldsMenuAction:(id)sender
{
    NSString *path = [sender representedObject];
    if (!path) return; 
    [[NSDocumentController sharedDocumentController] 
        openDocumentWithContentsOfFile:path display:YES];
}

#pragma mark -

- (void)log:(NSString *)format, ...
{
    NSString *final;
    va_list ap;
    
    va_start(ap, format);
    final = [[NSString alloc] initWithFormat:format arguments:ap];
    if (oConsoleView)
		[oConsoleView replaceCharactersInRange:NSMakeRange([[oConsoleView textStorage] length], 0) withString:final];
    NSLogv(final, ap);
    va_end(ap);
    
    if (oConsoleView)
		[oConsoleView scrollRangeToVisible:NSMakeRange([[oConsoleView textStorage] length], 0)];
}

@end
